<?php

namespace App\Services\ApplyGoldRecordUploadVoucher;

use App\Models\User;
use Illuminate\Support\Facades\Redis;
use App\Jobs\UploadGoldProductVoucherJob;
use App\Jobs\ExamineGoldProductPayingJob;
use App\Supports\Sms\Sms;
use Rainsens\Dinglog\Facades\Dinglog;

class ApplyGoldRecordUploadVoucher
{
	protected User $user;

	protected $unpaidCacheId = '';

	protected $voucher = '';

	public function __construct(User $user, $unpaidCacheId,$voucher)
	{
		$this->user = $user;
		$this->unpaidCacheId = $unpaidCacheId;
		$this->voucher = !empty($voucher)  ? $voucher : '';
	}

	public function upload()
	{
		if (!$this->unpaidCacheId) return;
		$recellCacheId = Redis::hGet($this->unpaidCacheId,'resell_record_cache_id');
		$recellUserId = Redis::hGet($this->unpaidCacheId,'resell_user_id');
		$isVoucher =Redis::hGet($this->unpaidCacheId,'voucher');
		$this->user->uploadRecordVoucher($this->unpaidCacheId,$this->voucher);
		if(!$isVoucher){

			 $this->user->addRecordToVoucherCache($recellCacheId,$this->unpaidCacheId);

		}
       
        $queue = app()->environment('local') ? 'default' : 'default';
        dispatch(new UploadGoldProductVoucherJob($this->user, $this->unpaidCacheId))->onQueue($queue);
        if($recellUserId){
         	$recellUser = User::find($recellUserId);
         	$recellUser->delRecordFromRunningCache($recellCacheId);
         	$recellUser->addRecordToRunningExamineCache($recellCacheId);
         	$phone = $recellUser->contact_phone ?? $recellUser->phone;
         	 $res = app(Sms::class)->phone($phone)
			    ->template(config("site.sms.code.template.examine"))
			    ->data('code', sms_code())->send();

			 Dinglog::text($res);
         	
         	$queue = app()->environment('local') ? 'default' : 'default';
         	dispatch(new ExamineGoldProductPayingJob($recellUser, $this->unpaidCacheId ,$recellCacheId))->onQueue($queue);
		
        }
       
	}
}
